/**
 * Created by Ysssssss on 2021/5/11.
 */
import React, { PureComponent } from 'react'
import {connect} from "react-redux";
import PageBackHeader from "@common/PageBackHeader";
import {getHistoryMatchParams} from "@utils/setUrlQuery";
import {Tabs, Checkbox, Upload, Progress, Table} from 'antd'
import notify from "@utils/tip";
// import {uploadQiniuFile} from "@utils/qiniu";
import { uploadCOSFile } from '@utils/cos'
import {withRouter} from "react-router-dom";
import {
    getProductImportTaskList,
    getProductImportTaskProgress,
    productImport
} from "@sagas/productCenter";
import BilinIcon from "@common/presentational/BilinIcon";


@withRouter
class ProductImportPage extends PureComponent {
    render () {
        const { productNature } = getHistoryMatchParams(this.props)
        return (
            <div className="bilin-web">
                <PageBackHeader title="导入商品" backUrl={productNature ? `/product-center/product/${productNature}/list` : '/main'}/>
                <div className="bilin-web-body product-import-page">
                    <Tabs>
                        <Tabs.TabPane tab="零售品导入" key="1">
                            <ProductImport productNature={1} />
                        </Tabs.TabPane>
                        <Tabs.TabPane tab="虚拟品导入" key="2">
                            <ProductImport productNature={2} />
                        </Tabs.TabPane>
                    </Tabs>
                </div>
            </div>
        )
    }
}

const UPLOAD_STATUS = {
    0: '已失败',
    1: '进行中',
    2: '已成功',
}

let columns = [{
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
}, {
    title: '上传时间',
    dataIndex: 'upload_time',
    key: 'upload_time',
}, {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => UPLOAD_STATUS[text]
}, {
    title: '详情',
    dataIndex: 'extra',
    key: 'extra',
}]

@connect(({ productCenter }) => ({
    productImportTaskListMap: productCenter.productImportTaskListMap
}), {
    getProductImportTaskList,
    getProductImportTaskProgress,
    productImport
})
class ProductImport extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            progress: null,
            uploadMode: false
        }
        this.taskTimout = null
    }

    componentDidMount() {
        this.getProductImportTaskList()
    }

    componentWillUnmount () {
        clearTimeout(this.taskTimout)
    }

    getProductImportTaskList () {
        const { productNature } = this.props
        this.props.getProductImportTaskList({
            productNature
        })
    }

    beforeUpload (file) {
        const _fileSize = file.size;
        if (_fileSize - 3 * 1024 * 1024 >= 0) {
            notify('文件大小不能超过3M', 'error')
            return false
        }
        return true
    }

    productUpload (key) {
        const { productNature } = this.props
        const { updateMode } = this.state
        this.props.productImport({
            productNature,
            link: key,
            updateMode
        }, id => {
            this.getProgress(id)
        })
    }

    getProgress (id) {
        this.props.getProductImportTaskProgress({
            id
        }, progress => {
            if (progress === 100 || progress === -1) {
                this.setState({
                    progress: null
                }, () => {
                    this.getProductImportTaskList()
                })
            } else {
                this.setState({
                    progress
                }, () => {
                    this.taskTimout = setTimeout(() => {
                        this.getProgress(id)
                    })
                })
            }
        })
    }

    uploadAction (file) {
        return new Promise(resolve => {
            console.log(file)
            this.setState({
                progress: 0
            })
            let uploadFunc = uploadCOSFile // uploadQiniuFile
            uploadFunc(file, 'excel', file.type.replace('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx').replace('application/vnd.ms-excel', 'xls'), res => {
                this.productUpload(res.key)
                resolve()
            }, () => {
                this.setState({
                    progress: null
                })
                resolve()
            })
        })
    }

    handleUploadModeChange (e) {
        this.setState({
            uploadMode: e.target.checked
        })
    }

    render () {
        const { productImportTaskListMap, productNature } = this.props
        const { uploadMode, progress } = this.state
        const productImportTaskList = productImportTaskListMap[productNature] || []
        return (
            <div className="mgt-48">
                <div className="flex-row-between ft-clr-ml">
                    <div>
                        <span>TIPS：请先下载模板，按照模板格式准确填写后上传</span>
                        <span className="clr-green mgl-24 cur-poi">下载模版</span>
                    </div>
                    <Checkbox checked={uploadMode} onChange={this.handleUploadModeChange.bind(this)}>
                        <span className="ft-14 ft-clr-ml mgl-8">文件上传覆盖同名商品信息</span>
                    </Checkbox>
                </div>
                <Upload.Dragger
                    name="importFile"
                    action={this.uploadAction.bind(this)}
                    accept=".xlsx, .xls, .csv"
                    beforeUpload={this.beforeUpload.bind(this)}
                    customRequest={() => {}}
                    className="upload-drag"
                    disabled={progress !== null}
                    showUploadList={false}
                >
                    { progress === null ? (
                        <>
                            <BilinIcon type="upload" className="ft-36 ft-clr-md"/>
                            <div className="ft-12 ft-clr-md mgt-14 w-100 txc">点击或者拖动文件到虚线框内上传</div>
                            <div className="ft-12 ft-clr-ml w-100 txc">上传文件：大小不超过3M,支持xls/xlsx/csv格式</div>
                        </>
                    ) : (
                        <Progress type="circle" percent={progress} />
                    ) }
                </Upload.Dragger>
                <div className="mgt-48">
                    <span>导入记录</span>
                    <span className="ft-clr-ml">（只展示最近20条）</span>
                </div>
                <Table
                    className="mgt-12"
                    columns={columns}
                    pagination={false}
                    dataSource={productImportTaskList.map(task => ({...task, key: task.id}))}
                />
            </div>
        )
    }
}

export default ProductImportPage